package cn.zy.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Author: Administrator
 * @Description:
 * @Date: Created in 16:48 2021/9/9
 * @Modified By:
 * @version: 1.0
 */
public final class PropsUtil {

	public static final Logger LOG = LoggerFactory.getLogger(PropsUtil.class);


	/**
	 * 加载熟悉文件
	 */

	public static Properties loadProps(String fileName) {

		Properties props = null;
		InputStream in = null;

		try {
			in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
			if (in == null) {
				throw new FileNotFoundException(fileName + " file not found!");
			}
			props = new Properties();
			props.load(in);
		} catch (IOException e) {
			LOG.error("load properties file failedl", e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					LOG.error("close inputstream failed", e);
				}
			}

		}
		return props;
	}


	public static String getString(Properties props, String key){

		return getString(props, key, "");
	}

	public static String getString(Properties props, String key, String defaultValue) {

		String value = defaultValue;
		if (props.containsKey(key)){
			value = props.getProperty(key);
		}
		return value;
	}

	public static int getInt(Properties props, String key){

		return getInt(props, key, 0);
	}

	public static int getInt(Properties props, String key, int defaultValue) {

		int value = defaultValue;
		if (props.containsKey(key)){
			value = CastUtil.castInt(props.getProperty(key));
		}
		return value;
	}


	public static boolean getBoolean(Properties props, String key){

		return getBoolean(props, key, false);
	}

	public static boolean getBoolean(Properties props, String key, boolean defaultValue) {

		boolean value = defaultValue;
		if (props.containsKey(key)){
			value = CastUtil.castBoolean(props.getProperty(key));
		}
		return value;
	}
}
